import axios from 'axios'
import {
  Message,
  MessageBox
} from 'element-ui'
import store from '../store'
import {
  getToken,
  removeToken
} from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 30000, // 请求超时时间
  headers: {
    version: Math.random(0, 1) * 123456789
  }
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code === 1) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 1 * 1000
      })
      return Promise.reject(response.data)
    } else if (res.code === 0) {
      return Promise.resolve(response.data)
    }
  },
  error => {
    const { response } = error
    console.log(error)
    // if (response.statusCode === 500) {
    //   Message.error({
    //     message: '服务器错误',
    //     type: 'error',
    //     duration: 2 * 1000
    //   })
    // }
    const { code } = response.data
    errorHandle(code, response.data)
    return Promise.reject(error)
  }
)
const errorHandle = (code, res) => {
  switch (code) {
    case 401:
      MessageBox.confirm(
        '你已被登出，可以取消继续留在该页面，或者重新登录',
        '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        console.log('sure')
        store.dispatch('user/resetToken').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        }).catch((e) => {
          console.log('cancle')
          removeToken()
        })
      })
      break
    case 402:
      Message.info({
        message: res.msg,
        type: 'error',
        duration: 2 * 1000,
        onClose() {
          window.location.href = '/'
        }
      })
      break
    case 403:
      Message.warning({
        message: res.msg,
        type: 'error',
        duration: 1 * 1000,
        onClose() {
          window.location.href = '#/system/attestation'
        }
      })
      break
    case 404:
      Message.warning({
        message: '您已被禁用',
        type: 'error',
        duration: 1 * 1000,
        onClose() {
          window.close()
        }
      })
      break
    default:
      break
  }
}

export default service
